import { useMemo } from "react";
import { useAppSelector } from "../store";
// 自定义hooks
// 方便获取购物车参数数据
export function useCar() {
  const car = useAppSelector((state) => state.car.car);

  const count = useMemo(() => {
    const count = car.reduce((p, n) => {
      return p + n.count;
    }, 0);
    return count === 0 ? "" : count;
  }, [car]);

  const price = useMemo(() => {
    return car.reduce((p, n) => {
      return p + n.count * n.price;
    }, 0);
  }, [car]);

  const selectCount = useMemo(() => {
    return car.reduce((p, n) => {
      return n.isChecked ? p + n.count : p;
    }, 0);
  }, [car]);

  const selectPrice = useMemo(() => {
    return car.reduce((p, n) => {
      return n.isChecked ? p + n.count * n.price : p;
    }, 0);
  }, [car]);

  const allCheck = useMemo(() => {
    return car.every((v) => v.isChecked);
  }, [car]);

  return {
    count,
    price,
    selectCount,
    selectPrice,
    allCheck,
  };
}
